import 'package:flutter/widgets.dart';
import 'package:flutter_base_framework/flutter_base_framework.dart';
import 'package:flutter_common_utils/flutter_common_utils.dart';
import 'package:flutter_refresh/flutter_refresh_export.dart';
import 'package:get/get.dart';
import 'package:flutter_live_data/live_data_export.dart';
import 'package:flutter_common_ui/flutter_common_ui.dart';

/// 所有viewModel的父类，提供一些公共功能
abstract class BaseViewModel {
  BuildContext get context {
    if (lifecycleOwner == null) {
      throw FlutterError('lifecycleOwner = null ');
    }
    return requireLife.context;
  }

  dynamic arguments;
  LifecycleOwner? lifecycleOwner;
  bool _isDispose = false;
  bool isFirst = true;

  LifecycleOwner get requireLife => lifecycleOwner!;

  //页面状态切换
  LoadStateController? get loadStateCtrl {
    if (lifecycleOwner == null) return null;
    if (lifecycleOwner is BaseWidgetState) {
      return (lifecycleOwner as BaseWidgetState).loadStateCtrl;
    }
    return null;
  }

  LoadStateController get requireLoadStateCtrl => loadStateCtrl!;

  //下拉刷新和加载更多分页
  AppRefreshController? get refreshCtrl {
    if (lifecycleOwner == null) return null;
    if (lifecycleOwner is BaseWidgetState) {
      return (lifecycleOwner as BaseWidgetState).refreshCtrl;
    }
    return null;
  }

  AppRefreshController get requireRefreshCtrl => refreshCtrl!;

  //分页
  PageHelper pageHelper = PageHelper();

  BaseViewModel();

  void initState() {
    arguments = arguments ?? (Get.arguments ?? {});
    //保证只调用一次
    if (isFirst) {
      isFirst = false;
      onCreate();
    }
  }

  bool get isDispose => _isDispose;

  @protected
  void onCreate() {}

  @mustCallSuper
  void dispose() {
    BaseCoreConfig.onDispose(this);
    _isDispose = true;
    lifecycleOwner = null;
  }
}
